package com.csi.bumblebee.service.impl;

import com.csi.bumblebee.domain.manage.Account;
import com.csi.bumblebee.domain.manage.AccountRole;
import com.csi.bumblebee.domain.manage.Role;
import com.csi.bumblebee.mapper.ManageMapper;
import com.csi.bumblebee.service.ManageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class ManageServiceImpl implements ManageService {

    @Autowired
    private ManageMapper manageMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 展示所有管理员账号
     * @return List<Account>
     */
    @Override
    public List<Account> list() {
        return manageMapper.list();
    }

    /**
     * 增加管理员账号
     * @param account 对象
     * @return 影响行数
     */
    @Override
    public int add(Account account) {
        int result = manageMapper.add(account);
        if (result > 0) {
            redisTemplate.opsForValue().set(account.getId(), account);
        }
        return result;
    }

    /**
     * 删除管理员账号
     * @param id 主键Id
     * @return 影响行数
     */
    @Override
    public int delete(String id) {
        int result = manageMapper.delete(id);
        if (result > 0){
            redisTemplate.delete(id);
        }
        return result;
    }

    /**
     * 登录
     * @param account 对象
     * @return account对象
     */
    @Override
    public Account login(String username,String password) {
        return manageMapper.login(username,password);
    }

    /**
     * 展示所有的角色
     * @return List<Role>
     */
    @Override
    public List<Role> listAllRole() {
        List<Role> roleList = (List<Role>) redisTemplate.opsForValue().get("rolesList");

        if (roleList != null) {
            return roleList;
        }else {
            roleList = manageMapper.listAllRole();
            redisTemplate.opsForValue().set("rolesList", roleList);
            return roleList;
        }
    }

    /**
     * 增加用户角色关联
     * @param accountRole 对象
     * @return 影响行数
     */
    @Override
    public int insertAccountRole(AccountRole accountRole) {
        return manageMapper.insertAccountRole(accountRole);
    }
}
